package com.ruoyi.boat.tcp.client;


import com.ruoyi.boat.codec.BdCodec;
import com.ruoyi.boat.codec.BdRes;
import com.ruoyi.boat.codec.MessageDecoder;
import com.ruoyi.boat.domain.*;
import com.ruoyi.boat.tcp.cache.CommunicationType;
import com.ruoyi.boat.tcp.cache.WaveBoat;
import com.ruoyi.boat.tcp.cache.MyApplicationCache;
import com.ruoyi.boat.tcp.server.RouteStatusEnum;
import com.ruoyi.boat.utils.ByteUtil;
import com.ruoyi.boat.utils.LocationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Handles a server-side channel.
 */

@Slf4j
public class TcpClientHandler extends ChannelInboundHandlerAdapter {

    NettyClient nettyClient;

    public TcpClientHandler(NettyClient nettyClient) {
        this.nettyClient = nettyClient;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        try {
            log.error("bd " + nettyClient.getBdType().getType() + " tcp client has exception", cause);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        log.warn("bd {} tcp client disconnected from tcp server", nettyClient.getBdType().getType());
        if (!nettyClient.connectFailed) {
            nettyClient.connectFailed = true;
            ctx.channel().eventLoop().schedule(nettyClient::start, 10, TimeUnit.SECONDS);
        }
    }
}